package com.pvdnc.tapkit.utils;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.util.SparseArray;

import java.util.Random;

import static android.os.Build.VERSION_CODES.O;


public class NotificationUtils {
    private final SparseArray<String> mLevelChannelMap=new SparseArray<>();

    private Context mContext;
    private NotificationManager mManager;

    public NotificationUtils(Context context){
        mContext=context;
        mManager= (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT<O)
            return;
        initChannels();
    }

    @TargetApi(O)
    private static NotificationChannel create(String name,int importance){
        return new NotificationChannel(name,name,importance);
    }

    public static final int LEVEL_IMPORTANT=1;

    public static final int LEVEL_NORMAL=0;

    @TargetApi(O)
    private void initChannels(){
        String important="important";
        mManager.createNotificationChannel(create(important,LEVEL_IMPORTANT));
        mLevelChannelMap.put(LEVEL_IMPORTANT,important);
        String normal="normal";
        mManager.createNotificationChannel(create(normal,LEVEL_NORMAL));
        mLevelChannelMap.put(LEVEL_NORMAL,normal);
    }

    public String getChannel(int level){
        return mLevelChannelMap.get(level);
    }

    public int notify(Notification.Builder builder,int level){
        int id=new Random().nextInt();
        if (Build.VERSION.SDK_INT >= O) {
            String channelId=getChannel(level);
            builder.setChannelId(channelId);
        }
        try {
            mManager.notify(id, builder.build());
            return id;
        }catch (Exception e){
            e.printStackTrace();
            return -1;
        }
    }
}
